import { FC } from 'react'
import { Form, Input, Button } from 'antd'
import { LoginType } from './loginApi'
import { useNavigate } from 'react-router-dom'
import { PoweroffOutlined } from '@ant-design/icons'
import { useAppDispatch, useAppSelector } from 'store/hooks'
import { fetchAsyncAction } from './loginSlice'

// set_token ---> action
interface HomePropsType {}

const Login: FC<HomePropsType> = (props) => {
  // const [loading, setLoading] = useState<boolean>(false)
  // 1. 路由跳转
  const navigate = useNavigate()
  // 2. 提交dispatch redux
  const dispatch = useAppDispatch()
  // 3. 获取selector redux
  const store = useAppSelector((s) => s.login)

  // 4. 提交
  const onFinish = async (values: LoginType) => {
    const res = await dispatch(fetchAsyncAction(values))
    console.log('res------------login:', res)
    if (res.payload.code === -1) {
      alert(res.payload.msg)
    } else {
      navigate('/home')
    }
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }

  return (
    <div>
      <Form name="basic" onFinish={onFinish} onFinishFailed={onFinishFailed}>
        <Form.Item label="账号" name="username">
          <Input />
        </Form.Item>
        <Form.Item label="密码" name="password">
          <Input.Password />
        </Form.Item>
        <Form.Item>
          <Button icon={<PoweroffOutlined />} loading={store.loading} type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Login
